package guiclient;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class StringSocket {
    private final Socket socket;
    private final ObjectInputStream in;
    private final ObjectOutputStream out;

    /**
     * Wrapper for a socket which opens streams and handles their closing along
     * with the socket
     * @param socket socket to wrap.
     * @throws java.io.IOException
     */
    public StringSocket(Socket socket) throws IOException {
        this.socket = socket;
        out = new ObjectOutputStream(socket.getOutputStream());
        in = new ObjectInputStream(socket.getInputStream());
    }

    /**
     * Read from socket
     * @return read string
     * @throws java.io.IOException
     */
    public String read() throws IOException  {
        try {
            synchronized (in) {
                return (String) in.readObject();
            }
        } catch (ClassNotFoundException e) {
            //("this should never happen");
        }
        return "";
    }

    /**
     * Write to socket
     * @param message string to write
     * @throws java.io.IOException
     */
    public void write(String message) throws IOException {
        synchronized (out) {
            out.writeObject(message);
            out.flush();
        }
    }

    public int available() throws IOException {
        return in.available();
    }

    /**
     * Close in and out streams and the socket.
     */
    public void close() {
        try {
            out.close();
        } catch (IOException ioException1) {
            //("can't close output stream because of" + ioException1.getMessage());
        } finally {
            try {
                in.close();
            } catch(IOException ioException2) {
                //("can't close input stream because of " + ioException2.getMessage());
            } finally {
                try {
                    socket.close();
                } catch (IOException ioException3) {
                    //("can't close socket because of " + ioException3.getMessage());
                }
            }
        }
    }

}